package LC;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode.com/problems/binary-tree-postorder-traversal/description/
 * Given a binary tree, return the postorder traversal of its nodes' values.
 * For example:
 * Given binary tree {1,#,2,3},
 * 1
 * \
 * 2
 * /
 * 3
 * return [3,2,1].
 * Note: Recursive solution is trivial, could you do it iteratively?
 */
public class LC_145_BinaryTreePostorderTraversal_Recur_Binary {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        List<Integer> lists = Solution_1.postorderTraversal(root);
        System.out.println(lists);
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    static class Solution_1 {
        static List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> result = new LinkedList<>();
            if (root != null) {
                Post_order(result, root.left);
                Post_order(result, root.right);
                result.add(root.val);
            }
            return result;
        }

        private static void Post_order(List<Integer> result, TreeNode curr) {
            if (curr != null) {
                Post_order(result, curr.left);
                Post_order(result, curr.right);
                result.add(curr.val);
            }
        }
    }

    static class Solution_2 {
        static List<Integer> list = new ArrayList<>();

        static List<Integer> postorderTraversal(TreeNode root) {
            if (root != null) {
                Stack<TreeNode> s1 = new Stack<>();
                Stack<TreeNode> s2 = new Stack<>();
                s1.push(root);
                while (!s1.isEmpty()) {
                    root = s1.pop();
                    s2.push(root);
                    if (root.left != null) s1.push(root.left);
                    if (root.right != null) s1.push(root.right);
                }
                while (!s2.isEmpty()) {
                    System.out.print(s2.pop().val + " ");
                    list.add(s2.pop().val);
                }
            }
            return list;
        }
    }
}